package com;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树的最大深度（队列实现）
 * User: YJ
 * Date: 2024-4-02
 * Time: 20:09
 */
public class maxDepthExerNonRecursion {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int maxDepth(TreeNode root) {
        // write code here
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        //根节点入队
        queue.offer(root);
        //记录深度
        int res = 0;
        //层序遍历
        while (!queue.isEmpty()) {
            int n = queue.size();
            //遍历这一层
            for (int i = 0; i < n; i++) {
                TreeNode t = queue.poll();
                if (t.left != null) {
                    queue.offer(t.left);
                }
                if (t.right != null) {
                    queue.offer(t.right);
                }
            }
            res++;
        }
        return res;
    }
}
